package com.yhp.filter;

import javax.servlet.*;
import javax.servlet.Filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest hsr = (HttpServletRequest) servletRequest;
        HttpServletResponse hsrp = (HttpServletResponse) servletResponse;
        String requestURI = hsr.getRequestURI();
        //Object txtUserName = hsr.getSession().getAttribute("TxtUserName");
        Object user = hsr.getSession().getAttribute("user");
        if(requestURI.endsWith("main.jsp") && user == null){
            System.out.println("检测到未登录");
            hsrp.setContentType("text/html;charset=utf-8");
            PrintWriter writer = hsrp.getWriter();
            writer.println("<script>location.href='index.jsp';alert('请登录！');</script>");
            //hsrp.sendRedirect("index.jsp");
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
